package com.baseweb.webadmin.controller.app;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import freemarker.template.SimpleDate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.security.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dsy62 on 2017-08-15.
 */
@Controller
@RequestMapping(value = "/appApiUser")
public class UserAppController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserOrderService userOrderService;

    /**
     * 添加日程
     * */
    @ResponseBody
    @RequestMapping(value = "/insertSchedule", method = RequestMethod.POST)
    public Map<String,Object> insertSchedule(@ModelAttribute()Schedule schedule){
        if(schedule.getUsername()!=null && !"".equals(schedule.getUsername())){
            schedule.setUsername(userService.selectUserById(schedule.getUserid()).getUsername());
        }
        if(userService.insertSchedule(schedule) > 0){
            return success(schedule,"添加成功");
        }else {
            return fail("添加失败");
        }
    }

    /**
     * 修改日程
     * */
    @ResponseBody
    @RequestMapping(value = "/updateSchedule", method = RequestMethod.POST)
    public Map<String,Object> updateSchedule(@ModelAttribute()Schedule schedule) {
        Schedule scheduleR = userService.findScheduleById(schedule.getId());
        scheduleR.setUserid(schedule.getUserid());
        if(schedule.getScheduledate()!=null && !"".equals(schedule.getScheduledate())){
            scheduleR.setScheduledate(schedule.getScheduledate());
        }
        if(schedule.getScheduletime()!=null && !"".equals(schedule.getScheduletime())){
            scheduleR.setScheduletime(schedule.getScheduletime());
        }
        if(schedule.getScheduletab()!=null && !"".equals(schedule.getScheduletab())){
            scheduleR.setScheduletab(schedule.getScheduletab());
        }
        if(schedule.getName()!=null && !"".equals(schedule.getName())){
            scheduleR.setName(schedule.getName());
        }
        if(schedule.getTel()!=null && !"".equals(schedule.getTel())){
            scheduleR.setTel(schedule.getTel());
        }
        if(schedule.getRemark()!=null && !"".equals(schedule.getRemark())){
            scheduleR.setRemark(schedule.getRemark());
        }
        if(schedule.getUsername()!=null && !"".equals(schedule.getUsername())){
            scheduleR.setUsername(userService.selectUserById(schedule.getUserid()).getUsername());
        }
        if(userService.updateSchedule(scheduleR)>0){
            return success(userService.findScheduleById(schedule.getId()),"修改成功");
        }else {
            return fail("修改失败");
        }
    }

    /**
     * 查询日程根据日期、时间、userid、username
     * */
    @ResponseBody
    @RequestMapping(value = "/findScheduleByWhere", method = RequestMethod.POST)
    public Map<String,Object> findScheduleByWhere(@RequestParam("scheduledate") String scheduledate,@RequestParam("scheduletime") String scheduletime,@RequestParam("userid") int userid,@RequestParam("username") String username){
        return success(userService.findScheduleByWhere(scheduledate,scheduletime,userid,username),"查询成功");
    }

    /**
     * 删除日程根据id
     * */
    @ResponseBody
    @RequestMapping(value = "/deleteScheduleByid", method = RequestMethod.GET)
    public Map<String,Object> deleteScheduleByid(@RequestParam("id") int id){
        if(userService.deleteScheduleByid(id)>0){
            return success("删除成功");
        }else {
            return fail("删除失败");
        }
    }

    /**
     * 根据Userid，时间段查询所有的档期
     * */
    @ResponseBody
    @RequestMapping(value = "/findScheduleByUserIdDate", method = RequestMethod.POST)
    public Map<String,Object> findScheduleByUserIdDate(@RequestParam("userid") int userid,@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime){
        return success(userService.findAllByUserIdDate(userid,startTime,endTime),"添加成功");
    }

    /**
     * 修改档期为不接单
     * */
    @ResponseBody
    @RequestMapping(value = "/udpateStatusById", method = RequestMethod.GET)
    public Map<String,Object> udpateStatusById(@RequestParam(value = "userId", required = false) Integer userId,
                                               @RequestParam(value = "scheduleDate", required = false) String scheduleDate,
                                               @RequestParam(value = "scheduleType", required = false) String scheduleType,
                                               @RequestParam(value = "status", required = false) Integer status) {
        if (userId == null) {
            return fail("请传入用户ID。参数名称：userId");
        } else if (scheduleDate == null || "".equals(scheduleDate)) {
            return fail("请传入档期。参数名称：scheduleDate；参数格式：yyyy-MM-dd");
        } else if (scheduleType == null || (!"1".equals(scheduleType) && !"2".equals(scheduleType))) {
            return fail("请传入档期类型。参数名称：scheduleType；参数值：1-午宴；2-晚宴");
        } else if (status == null || (status != -1 && status != 1)) {
            return fail("请传入状态码。参数名称：status；参数值：1-已接单或不接单；-1 -可接单");
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                sdf.parse(scheduleDate);
            } catch (ParseException e) {
                return fail("请传入正规的时间格式的档期，格式“yyyy-MM-dd”");
            }
        }

        int result = 0;
        if (status == -1) {
            result = userOrderService.selectOrderUnfinished(userId, scheduleDate, scheduleType);
        }
        if ((status == -1 && result == 0) || status == 1) {
            if (status == 1) {
                ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
                byUserBizSchedule.setUserId(userId);
                byUserBizSchedule.setScheduleDate(DateTime.parse(scheduleDate));
                byUserBizSchedule.setScheduleType(Integer.valueOf(scheduleType));
                result = userOrderService.insertSchedule(byUserBizSchedule);
            } else {
                result = userOrderService.deleteSchedule(Integer.valueOf(scheduleType), DateTime.parse(scheduleDate), userId);
            }
            if (result > 0) {
                return success("修改成功");
            } else {
                return fail("修改失败");
            }
        } else {
            return fail("该档期内有未完成的订单，不允许取消！");
        }
    }

    /**
     * 档期添加
     * */
    @ResponseBody
    @RequestMapping(value = "/insertStatusById", method = RequestMethod.POST)
    public Map<String,Object> insertStatusById(@RequestParam("userid") int userid,@RequestParam("status") int status,@RequestParam("scheduleDate") String scheduleDate,@RequestParam("scheduleType") int scheduleType){
        ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
        byUserBizSchedule.setUserId(userid);
        byUserBizSchedule.setScheduleDate(DateUtil.getDateTime(scheduleDate));
        byUserBizSchedule.setStatus(status);
        byUserBizSchedule.setScheduleType(scheduleType);
        byUserBizSchedule.setCreateTime(new DateTime());
        byUserBizSchedule.setUpdateTime(new DateTime());

        if(userOrderService.insertSchedule(byUserBizSchedule)>0){
            return success(byUserBizSchedule,"添加成功");
        }else {
            return fail("添加失败");
        }
    }

    /**
     * 添加提现记录
     * */
    @ResponseBody
    @RequestMapping(value = "/insertCardLog", method = RequestMethod.POST)
    public Map<String,Object> insertCardLog(@ModelAttribute()CardLog cardLog){
        User user = userService.selectUserById(cardLog.getUserid());
        if(user.getMoney().compareTo(new BigDecimal(cardLog.getMoney())) == -1 ){
            return fail("提现金额大于账户余额");
        }else{
            cardLog.setStatus("2");
            cardLog.setUpdater(cardLog.getCreater());
            cardLog.setCreatetime(DateUtils.getDate());
            cardLog.setUpdatetime(DateUtils.getDate());
            if(userService.insertCardLog(cardLog)>0){
                int oldMoney = user.getMoney().intValue();
                user.setMoney(new BigDecimal(oldMoney-Float.parseFloat(cardLog.getMoney())));
                userService.updateUser(user);
                return success(cardLog,"添加成功");
            }else {
                return fail("添加失败");
            }
        }
    }

    /**
     * 修改提现记录
     * */
    @ResponseBody
    @RequestMapping(value = "/updateCardLogById", method = RequestMethod.POST)
    public Map<String,Object> updateCardLogById(@ModelAttribute()CardLog cardLog){
        CardLog cardLogR = userService.findCardLogById(cardLog.getId());
        if(cardLog.getMoney()!=null && !"".equals(cardLog.getMoney())){
            cardLogR.setMoney(cardLog.getMoney());
        }
        cardLogR.setStatus(cardLog.getStatus());
        cardLogR.setUpdater(cardLog.getUpdater());
        cardLogR.setUpdatetime(DateUtils.getDate());
        if(userService.updateCardLogById(cardLogR)>0){
            //写记录
            ByMoneyLog byMoneyLog = new ByMoneyLog();
            byMoneyLog.setUserId(cardLogR.getUserid());
            byMoneyLog.setMoneyType(4);
            byMoneyLog.setAmount(new BigDecimal("-"+cardLogR.getMoney()));
            if("3".equals(cardLog.getStatus())){
                User user = userService.selectUserById(cardLogR.getUserid());
                int oldMoney = user.getMoney().intValue();
                user.setMoney(new BigDecimal(oldMoney+Float.parseFloat(cardLogR.getMoney())));
                userService.updateUser(user);
                byMoneyLog.setAmount(new BigDecimal(cardLogR.getMoney()));
            }
            byMoneyLog.setCreateTime(new DateTime());
            userService.insertSelectiveByMoneyLog(byMoneyLog);
            return success(cardLogR,"修改成功");
        }else {
            return fail("修改失败");
        }
    }

    /**
     * 查询提现记录根据createtime段
     * */
    @ResponseBody
    @RequestMapping(value = "/findAllCardLogByCreateTime", method = RequestMethod.POST)
    public Map<String,Object> findAllCardLogByCreateTime(@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime,@RequestParam("status") String status,@RequestParam("userid") int userid){
        return success(userService.findAllCardLogByCreateTime(startTime,endTime,status,userid),"查询成功");
    }

    /**
     * 银行卡查询全部根据userid
     * */
    @ResponseBody
    @RequestMapping(value = "/findAllCard", method = RequestMethod.POST)
    public Map<String,Object> findAllCard(@RequestParam("userid") int userid){
        return success(userService.findAllCard(userid),"查询成功");
    }

    /**
     * 银行卡添加
     * */
    @ResponseBody
    @RequestMapping(value = "/insertCard", method = RequestMethod.POST)
    public Map<String,Object> insertCard(@ModelAttribute()Card card){
        card.setStatus("1");
        if(userService.insertCard(card) > 0){
            return success(card,"添加成功");
        }else {
            return fail("添加失败");
        }
    }

    /**
     * 修改银行卡信息
     * */
    @ResponseBody
    @RequestMapping(value = "/updateCardById", method = RequestMethod.POST)
    public Map<String,Object> updateCardById(@ModelAttribute()Card card){
        Card cardR = userService.findCardById(card.getId());
        if(card.getName()!=null && !"".equals(card.getName())){
            cardR.setName(card.getName());
        }
        if(card.getCardname()!=null && !"".equals(card.getCardname())){
            cardR.setCardname(card.getCardname());
        }
        if(card.getCardnumber()!=null && !"".equals(card.getCardnumber())){
            cardR.setCardnumber(card.getCardnumber());
        }
        if(card.getCardno()!=null && !"".equals(card.getCardno())){
            cardR.setCardno(card.getCardno());
        }
        if(card.getStatus()!=null && !"".equals(card.getStatus())){
            cardR.setStatus(card.getStatus());
        }
        cardR.setUserid(card.getUserid());
        cardR.setUsername(card.getUsername());
        if(userService.updateCardById(cardR)>0){
            return success(cardR,"修改成功");
        }else {
            return fail("修改失败");
        }
    }

    /**
     * 个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/myPersonal", method = RequestMethod.POST)
    public Map<String,Object> myPersonal(@RequestParam(value = "mobile", defaultValue = "") String mobile){
        User user = userService.findUserByUserName(mobile);
        List<ByUserBizAuth> byUserBizAuthList = userService.findUserBizAuthByUserId(user.getId());
        if(byUserBizAuthList!=null){
            user.setUserBizAuth(byUserBizAuthList);
        }
        //信誉
        Role creditRole = roleService.findRoleByUserIdType(user.getId(), "4");
        if (creditRole != null) {
            user.setCreditData(creditRole.getRemark());
        }
        return success(user,"查询成功");
    }

    /**
     * 修改个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public Map<String,Object> updateUser(@ModelAttribute()User user,@RequestParam(value = "file", required = false) MultipartFile file){
        User userV = userService.selectByUserName(user.getUsername());
        user.setId(userV.getId());
        try{
            //图片上传
            if (file != null && file.getSize() > 0){
                String avatar_img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

                UploadUtil.uploadData(file.getBytes(), avatar_img_url);

                user.setBizCover(avatar_img_url);
                user.setAvatar(avatar_img_url);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        if(userService.updateUser(user) == 1){
            return success(userService.selectByUserName(user.getUsername()),"修改成功");
        }else{
            return fail("修改失败");
        }
    }

    /**
     * 查询商家列表
     * */
    @ResponseBody
    @RequestMapping(value = "/findAllUserList", method = RequestMethod.POST)
    public Map<String,Object> findAllUserList(@ModelAttribute()AppUserList appUserList,@RequestParam("page") int page, @RequestParam("pageNum") int pageNum){
        String startPrice = "0";
        String endPrice = "99999999";
        String orders = "id ";
        String wedding = "";
        String cnName="%%";
        if(appUserList.getWedding() != null){
            wedding = appUserList.getWedding();
        }
        if(appUserList.getPrice_type() != null){
            if("1".equals(appUserList.getPrice_type())){
                startPrice = "0";
                endPrice = "5000";
            }else if("2".equals(appUserList.getPrice_type())){
                startPrice = "5000";
                endPrice = "10000";
            }else if("3".equals(appUserList.getPrice_type())){
                startPrice = "10000";
                endPrice = "20000";
            }else if("4".equals(appUserList.getPrice_type())){
                startPrice = "20000";
                endPrice = "30000";
            }else if("5".equals(appUserList.getPrice_type())){
                startPrice = "30000";
                endPrice = "50000";
            }else if("6".equals(appUserList.getPrice_type())){
                startPrice = "50000";
                endPrice = "99999999";
            }
        }
        if(appUserList.getOrder() != null){
            if("biz_view_count".equals(appUserList.getOrder())){
                orders = "biz_view_count,id ";
            }else if("biz_view_count_desc".equals(appUserList.getOrder())){
                orders = "biz_view_count,id desc ";
            }else if("biz_star".equals(appUserList.getOrder())){
                orders = "biz_star,id ";
            }else if("biz_star_desc".equals(appUserList.getOrder())){
                orders = "biz_star,id desc ";
            }else if("biz_price".equals(appUserList.getOrder())){
                orders = "biz_price,id ";
            }else if("biz_price_desc".equals(appUserList.getOrder())){
                orders = "biz_price,id desc ";
            }
        }
        if(appUserList.getCn_name()!=null){
            cnName = "%"+appUserList.getCn_name()+"%";
        }
        List<AppUserList> lists = userService.findAllUserList(appUserList.getArea(),startPrice,endPrice,wedding,orders,(page-1)*pageNum,pageNum,appUserList.getRole_type_id(),cnName);

        //总记录数
        int numSum = userService.countUserList(appUserList.getArea(),startPrice,endPrice,wedding,orders,appUserList.getRole_type_id(),cnName);
        //总页数
        int pageSum = (numSum>pageNum?(numSum/pageNum):1);
        if(numSum % pageNum > 0 && numSum > pageNum){
            pageSum += 1;
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("UserList",lists);
        map.put("numSum",numSum);
        map.put("pageSum",pageSum);
        return success(map,"查询成功");
    }
}
